require(["./config"], () => {
    require(["jquery", "template", "request", "header", "nav", "footer", "zoom"], ($, template, req, Header) => {
        class Item{
            constructor() {
                this.idStr = null;
                this.itemObj = null;
                this.imgUrl = null;
                this.init();
            }
            init() {
                this.pageInit()
                .then(() => {
                    this.jsInit()
                })
                
            }
            pageInit() {
                new Header();
                const urlStr = location.href + "";
                // console.log(urlStr)
                if (urlStr.match(/\?id=\d+/)) {
                    this.idStr = urlStr.match(/\?id=\d+/)[0].match(/\d+/)[0]
                    // console.log(this.idStr);
                }
                return req.itemData(this.idStr)
                .then((res) => {
                    // console.log(res)

                    if (res.code === 0) {
                        this.itemObj = res.data.list[0];
                        // console.log(this.itemObj);

                        // 获取商品小图数据
                        const smallImgList = this.itemObj.shop_info.ali_images;
                        // console.log(this.itemImgList)
                        // 渲染图片小图
                        const htmlStr1 = template("smallImgBoxTemplate", {data : smallImgList});
                        // console.log(htmlStr1)
                        $("#smallImgBoxTemplateBox").html(htmlStr1);
                            $("#smallImgBoxTemplateBox li:first-of-type ")
                            .addClass("active")
                        
                        // 获取商品大图数据
                        const bigImgUrl = this.itemObj.shop_info.ali_image;
                        this.imgUrl = bigImgUrl;
                        $(".bigImgBox img")
                        .attr("src", bigImgUrl)

                        // 设置信息区中各单项数据
                        // 大标题与小标题
                        $(".message .titleBox h2")
                        .text(this.itemObj.shop_info.title)
                        .next()
                        .text(this.itemObj.shop_info.sub_title)
                        // 价格
                        $(".message .titleBox .priceBox p span")
                        .text(this.itemObj.spu.price)
                        $("#totalPrice").text(this.itemObj.spu.price);
                        // 汇总区数据
                        // 大标题
                        $("#totalTitle").text(this.itemObj.shop_info.title)
                        // 类型
                        this.itemObj.spu.sku_info.forEach((item) => {
                            if (this.idStr == item.sku_id) {
                                $("#totalType").text(item.spec_json[0].item_value)
                            }
                        })
                        

                        // 获取商品详情数据
                        let itemMsgImg = null
                        if (this.itemObj.shop_info.tpl_content.base.images.ali.url) {
                            itemMsgImg = this.itemObj.shop_info.tpl_content.base.images.ali.url[0] + "";
                        } else if (this.itemObj.shop_info.tpl_content.base.images.ali_mobile.url) {
                            itemMsgImg = this.itemObj.shop_info.tpl_content.base.images.ali_mobile.url[0] + "";
                        }
                        // console.log(this.itemMsgImg)
                        // 渲染详情
                        $(".details .details-content img")
                        .attr("src", itemMsgImg)

                    }
                    return req.commendData();
                })
                .then((res) => {
                    if (res.code ===0) {
                        // console.log(res);
                        let list = res.data.list;
                        let goodsList = [];
                        // 从list中随机获取8各数据放入goodsList
                        for (let n = 0; n <8; n++) {
                            let length = list.length;
                            let index = Math.floor(Math.random() * length)
                            // console.log(list[index])
                            goodsList.push(list[index])
                            list.splice(index, 1)
                        }
                        // console.log(goodsList)

                        // 渲染推荐项
                        const htmlStr = template("commendTemplate", {data : goodsList})
                        // console.log(htmlStr)
                        $("#commendTemplateBox").html(htmlStr);

                    }
                })

            }
            jsInit() {
                // console.log(this.itemObj)
                const _this = this;

                // 放大镜效果
                $("#bigImgZoom")
                .elevateZoom({
                    zoomType : "window",
                    // lensSize: 1,
                    zoomWindowWidth: 400,
                    zoomWindowHeight: 400,
                    zoomWindowPosition : 1,
                    zoomWindowOffsetx : 800
                })

                // 小图添加焦点
                $(".message .smallImgBox")
                .on("click", "li", function () {
                    // console.log(this);
                    $(this)
                    .addClass("active")
                    .siblings()
                    .removeClass("active")
                    $(".message .bigImgBox img")
                    .attr("src", $(this).find("img").attr("src"))
                    $("#bigImgZoom")
                    .elevateZoom({
                        zoomType : "window",
                        zoomWindowWidth: 400,
                        zoomWindowHeight: 400,
                        zoomWindowPosition : 1,
                        zoomWindowOffsetx : 100,
                        zoomWindowOffsety : 100
                    })
                })

                // 设置页面标题
                $("head title")
                .text(this.itemObj.shop_info.title);


                


                // 商品信息区数量变化
                $(".message .upBtn").click(function()  {
                    // console.log(this);
                    let num = $(this).prev().text() -0;
                    num++;
                    // console.log(num)
                    $(this).prev().text(num);
                    $("#totalCount").text(num);
                    let totalPrice = Math.round($("#price").text() * num * 10) / 10;
                    $("#totalPrice").text(totalPrice);
                })
                $(".message .downBtn").click(function() {
                    let num = $(this).next().text() - 0;
                    if (num <= 1) {
                        num = 1;
                    } else {
                        num--;
                    }
                    $(this).next().text(num);
                    $("#totalCount").text(num);
                    let totalPrice = Math.round($("#price").text() * num * 10) / 10;
                    $("#totalPrice").text(totalPrice);
                })

                // 点击添加购物车按钮事
                $("#cartNowBtn")
                .click(function () {
                    $(".buyBar .congratulation")
                    .fadeIn(1000, () => {
                        setTimeout(() => {
                            $(".buyBar .congratulation")
                            .fadeOut(1000)
                        }, 500)
                    })
                    // 添加购物车数据处理
                    let hasCart = false;
                    let hasUser = false;
                    let hasGoods = false;
                    let userIndex = null;
                    let goodsIndex = null;
                    let userTel = localStorage.getItem("currentUser");
                    // console.log(userTel)
                    let goodsPageList = {
                        "goodsId" : _this.idStr,
                        "imgUrl" : _this.imgUrl,
                        "title" : $("#totalTitle").text(),
                        "type" : $("#totalType").text(),
                        "price" : $("#price").text(),
                        "count" : $("#totalCount").text() - 0,
                        "checked" : true
                    }
                    // console.log(goodsList);
                    let cartData = JSON.parse(localStorage.getItem("cartData"));
                    hasCart = cartData && cartData.cartList ? true : false;
                    if (hasCart) {
                        cartData.cartList.forEach((item, index) => {
                            if (item.userTel === userTel) {
                                userIndex = index;
                                hasUser = true;
                                return
                            }
                        })
                    }
                    if (hasUser) {
                        cartData.cartList[userIndex].goodsList.forEach((item, index) => {
                            if (item.goodsId === goodsPageList.goodsId) {
                                goodsIndex = index;
                                hasGoods = true;
                                return
                            }
                        })
                    }
                    if (!hasCart) {
                        cartData = {
                            "cartList" : [{
                                "userTel" : userTel,
                                "goodsList" : [goodsPageList]
                            }]
                        }
                    }
                    if (hasCart && !hasUser) {
                        cartData.cartList.push({
                            "userTel" : userTel,
                            "goodsList" : [goodsPageList]
                        })
                        
                    }
                    if (hasCart && hasUser && !hasGoods) {
                        cartData.cartList[userIndex].goodsList.push(goodsPageList);
                    }
                    if (hasCart && hasUser && hasGoods) {
                        cartData.cartList[userIndex].goodsList[goodsIndex].count += goodsPageList.count;
                    }
                    localStorage.setItem("cartData", JSON.stringify(cartData));
                    new Header();
                })

                // 回到顶部事件
                $(".toTopBox .toTop")
                .click(function () {
                    $(window).scrollTop(0);
                })
            }

        }
        new Item();
    })
})